<template>
  <div class="shell">
    <div class="talk">
      <div class="text">
        <h4>聊天室</h4>
        <!-- 消息显示区域 -->
        <div id="text-shell" ref="shell">
          <!-- 循环渲染消息列表 -->
          <div v-for="(item, index) in info" :key="index" class="mes">
            <!-- 如果消息发送者不是当前用户，显示在左侧 -->
            <div class="mes-per" v-if="username != item.name">
              <img :src="`${item.photourl}`" alt="" />
              <div>
                <h6>{{ item.name }}</h6>
                <span>{{ item.message }}</span>
              </div>
            </div>
            <!-- 如果消息发送者是当前用户，则显示在右侧 -->
            <div class="mes-per mes-self" v-else>
              <img :src="`${item.photourl}`" alt="" />
              <div>
                <h6>{{ item.name }}</h6>
                <span>{{ item.message }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 消息输入区域 -->
      <div class="inp" @keydown="prevent($event)">
        <textarea
          type="text"
          ref="text"
          v-model="content"
          placeholder="输入文字，和大伙一起交流经验叭"
        ></textarea>
        <button @click="subText">发送</button>
      </div>
    </div>
  </div>
</template>
  
  <script>
  export default {
    data() {
      return {
        content: '',
        info: [],
        username: '',
        scrolltop: 0,
        accinterval: 0,
        // baseUrl: '',
      }
    },
    // 退出页面时,清理轮询计时器
    beforeUnmount(){
      clearInterval(this.accinterval);
    },
    created() {
      // this.baseUrl = this.$store.state.baseUrl;
      this.username = this.$store.state.userInfo.mname||'';
      this.getMes(true)
      this.accinterval = setInterval(this.getMes, 1000)
    },
    mounted() {
      // 监听滚动条滚动事件存储滚动条的位置，方便回归
      this.$refs.shell.addEventListener(
        'scroll',
        () => {
          this.$nextTick(() => {
            this.scrolltop = this.$refs.shell.scrollTop
          })
        },
        true
      )
    },
    methods: {
      // 发送消息
      subText() { 
        if (this.content == '') {
          return this.$tools.alertMsg("消息不能为空", "error");
        }
        // 保存外部作用域
        const that = this
        // 计算时间
        that.$axios
          .get("message/sendMessage", { params: { mid: that.$store.state.mid,message:that.content } })
          .then((response) => {
            that.content = ''
            that.getMes(true)
            console.log(response)
          }).catch(function (error) {
            console.log(error)
          });
      },
      // 获取消息
      getMes(me) {
        const that = this
        that.$axios.get("message/getMessage").then((response) => {
            console.log(response)

            that.info = response.data.data.reverse();
            
            that.info.forEach((item)=>{
              if(!item.photourl.startsWith('http')) item.photourl = `${that.$store.state.baseUrl}/${item.photourl}`
            })
            if (me) that.scroll()
          }).catch(function (error) {
            console.log(error)
          });
      },
      // 检测是否回车阻止默认事件并发送请求，不然回车输出会多一个空格
      prevent(event) {
        if (event.keyCode === 13) {
          event.preventDefault()
          this.subText()
        }
      },
      // 滚动消息区域到底部
      scroll() {
        var ele = this.$refs.shell
        // 下一次数据更新完之后才触发
        this.$nextTick(() => {
          if (ele.scrollHeight > ele.clientHeight) {
            //设置滚动条到最底部，平滑移动
            ele.scrollTo({ top: ele.scrollHeight, behavior: 'smooth' })
          }
        })
      },
    },
  }
  </script>
  
  <style scoped lang="less">
  .shell {
    height: calc(100vh - 72px);
    position: relative;
    .talk {
      position: relative;
      width: 830px;
      height: 540px;
      margin: 10px auto;
      background-color: #0d1722;
      .text {
        width: 830px;
        height: 416px;
        border-bottom: 2px solid #1A2A3C;
        h4 {
          width: 830px;
          height: 36px;
          line-height: 36px;
          color: #fff;
          font-size: 17px;
          font-weight: bold;
          text-align: center;
          background-color: rgb(74, 142, 209);
        }
        #text-shell {
          position: relative;
          width: 830px;
          height: 380px;
          overflow: hidden auto;
          &::-webkit-scrollbar {
            display: none; /* Chrome, Safari, Opera */
          }
          .mes {
            .mes-per {
              position: relative;
              margin: 14px 15px 6px 15px;
              text-align: left;
              img {
                width: 34px;
                height: 34px;
                margin: 0px 5px;
                border-radius: 50%;
                display: inline-block;
                vertical-align: top;
              }
              div {
                display: inline-block;
                word-break: break-all;
                h6 {
                  color: #fff;
                  font-size: 12px;
                  text-indent: 6px;
                }
                span {
                  display: inline-block;
                  max-width: 700px;
                  // margin-top: -4px;
                  font-size: 13px;
                  background: #12B7F5;
                  padding: 4px 8px;
                  border-radius: 5px;
                  white-space: pre-wrap;
                  color: #000;
                }
              }
            }
            .mes-self {
              // 自己的发言时放到右边
              direction: rtl;
              text-align: right;
              span {
                text-align: left;
                direction: ltr;
              }
            }
          }
        }
      }
      .inp {
        width: 100%;
        height: 124px;
        overflow: hidden;
        text-align: right;
        background-color: #0d1722;
        textarea {
          background-color: #0d1722;
          color: #fff;
          width: 100%;
          padding: 6px 10px 5px 7px;
          box-sizing: border-box;
          height: 86px;
          resize: none;
          border: none;
          outline: none;
          font-size: 13px;
          &::-webkit-scrollbar {
            display: none; /* Chrome, Safari, Opera */
          }
        }
        button {
          width: 86px;
          height: 26px;
          font-size: 14px;
          margin-right: 8px;
          font-weight: bold;
          border-radius: 2px;
          background-color: rgb(64, 158, 255);
          color: #fff;
        }
      }
    }
  }
  </style>
  